package com.sencorsta.ids.talk.OpenHandler;

import com.alibaba.fastjson.JSONObject;
import com.google.protobuf.InvalidProtocolBufferException;
import com.sencorsta.ids.common.information.ErrorCodeList;
import com.sencorsta.ids.common.proto.utils.ReturnUtils;
import com.sencorsta.ids.common.service.MsgService;
import com.sencorsta.ids.common.service.RedisService;
import com.sencorsta.ids.core.entity.ClientEvent;
import com.sencorsta.ids.core.log.Out;
import com.sencorsta.ids.core.tcp.opensocket.OpenMessageHandler;
import com.sencorsta.ids.core.tcp.socket.protocol.RpcMessage;
import com.sencorsta.ids.talk.proto.ImtalkPushReturnFriendsMsg;
import com.sencorsta.ids.talk.proto.ImtalkSendAddFriendsRequestByProto;
import io.netty.channel.Channel;

/**
* @description: 添加好友
* @author TAO
* @date 2019/6/19 9:24
*/
@ClientEvent("AddFfriend")
public class AddFfriendHandler extends OpenMessageHandler implements RedisService {

    @Override
    public RpcMessage request(Channel channel, JSONObject json, String content, byte[] data, byte[] protobuf) {
        Out.debug("----------------------------------添加好友AddFfriend----------------------------------------");

        //创建添加好友的Proto的res返回前端的对象
        ImtalkSendAddFriendsRequestByProto.AddFriendsRequestRes.Builder res=ImtalkSendAddFriendsRequestByProto.AddFriendsRequestRes.newBuilder();
        //创建推送好友信息的Proto
        ImtalkPushReturnFriendsMsg.PushReturnFriends.Builder push=ImtalkPushReturnFriendsMsg.PushReturnFriends.newBuilder();
        try{
            //创建添加好友的Proto的req接收前端数据的对象
            ImtalkSendAddFriendsRequestByProto.AddFriendsRequestReq req=ImtalkSendAddFriendsRequestByProto.AddFriendsRequestReq.parseFrom(protobuf);

            //用户id
            String useId=userId;
            //目标用户id
            String tagId=req.getTagId();
            //携带备注内容
            String remar=req.getRemar();

            if (useId.equals(tagId)){
                Out.debug("-------------------傻逼么自己加自己！！！！----------------------------");
                return responseProto(res.setMsg(ReturnUtils.ErrorProto(ErrorCodeList.I_ADD_IS_ERROR)));
            }


            Out.debug("发起搜索的用户id"+useId);
            Out.debug("目标用户的id"+tagId);
            Out.debug("添加好友备注信息"+remar);

            //标识信息
            res.setSign(req.getSign());//返回前端标识信息
            //将用户信息添加到run
            push.setUserId(userId);
            push.setRemark(remar);

            //将run携带的用户信息由服务器推送给发起搜索用户

            MsgService.pushAndSaved(pushProto(tagId,"push.ReturnTag",push));

            res.setMsg(ReturnUtils.ErrorProto(ErrorCodeList.SUCCESS));
            return responseProto(res);
        }catch (InvalidProtocolBufferException e){
            e.printStackTrace();
            return responseProto(res.setMsg(ReturnUtils.ErrorProto(ErrorCodeList.SERVER_ERROR)));
        }
    }

}
